package vsy.buzzwordbingo.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import vsy.buzzwordbingo.model.GameBoard;
import vsy.buzzwordbingo.model.GameCore;
import vsy.buzzwordbingo.model.Player;

@Controller
public class GameController {

	@Resource
	private GameCore gameCore;
	
	@Resource
	private Long ajaxGamePollInterval;

	@RequestMapping(value = "/game/{gameId}", method = RequestMethod.GET)
	public ModelAndView getGame(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String gameId) {
		String playerName = request.getUserPrincipal().getName();
		
		GameBoard board = gameCore.joinGame(gameId, playerName);

		
//		if (game == null) {
//			return createEmptyResponse("text/html", HttpStatus.NOT_FOUND);
//		}
		
		Player player = gameCore.getPlayer(playerName);
		request.setAttribute("sessionId", request.getSession().getId());
		request.setAttribute("player", player);
		request.setAttribute("game", board.getGame());
		request.setAttribute("board", board);
		request.setAttribute("pollInterval", ajaxGamePollInterval);
		return new ModelAndView("game");
	}
	

	
	
	@RequestMapping(value = "/json/games/{gameId}/players", method = RequestMethod.DELETE)
	public ModelAndView deletePlayerFromGame(HttpServletRequest request,
			HttpServletResponse response, final @PathVariable String gameId) {

		System.out.println("delete Player");
		String playerName = request.getUserPrincipal().getName();
		gameCore.leaveGame(gameId, playerName);
		
		return new ModelAndView(new View() {

			@Override
			public String getContentType() {
				return "application/json";
			}

			@Override
			public void render(Map<String, ?> model,
					HttpServletRequest request, HttpServletResponse response)
					throws Exception {
			    response.setStatus(HttpStatus.OK.value());
			}
		});
	}
}